package com.ghsc.ghxc.jsb.ui.message.activity

import android.R.bool
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import com.cn.appcore.base.BaseVMActivity
import com.cn.appcore.event.RxBus
import com.cn.appcore.event.RxBusBean
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.setSingleClickListener
import com.cn.appcore.ext.showToast
import com.cn.appcore.ext.visible
import com.cn.appcore.http.constant.HttpConstant
import com.cn.appcore.utils.GlideUtil
import com.cn.appcore.utils.GsonUtil
import com.cn.appcore.utils.Preference
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.CustSignKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.databinding.ActivitySetSingleBinding
import com.ghsc.ghxc.jsb.ext.gone
import com.ghsc.ghxc.jsb.ui.message.bean.GroupUserInfoDataBean
import com.ghsc.ghxc.jsb.ui.message.view.CustMsgType
import com.ghsc.ghxc.jsb.ui.message.view.RouterUtils
import com.ghsc.ghxc.jsb.view.ConfirmCancelPopViiew
import com.google.gson.Gson
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.netease.nimlib.sdk.NIMClient
import com.netease.nimlib.sdk.RequestCallback
import com.netease.nimlib.sdk.msg.MsgService
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum
import com.netease.nimlib.sdk.msg.model.StickTopSessionInfo
import com.netease.nimlib.sdk.uinfo.UserService
import com.netease.nimlib.sdk.uinfo.model.NimUserInfo
import com.netease.yunxin.kit.chatkit.repo.ConversationRepo
import com.netease.yunxin.kit.chatkit.ui.bean.ExtDataBean
import com.netease.yunxin.kit.chatkit.ui.common.ChatCallback
import com.netease.yunxin.kit.corekit.im.provider.FetchCallback


/**
 * 项目：GuoHuaJsb
 * 包名：com.ghsc.ghxc.jsb.ui.message.activity
 * 类名：ChatSetSingleActivity
 * 创建时间：2024/5/8 12:06
 * 创建人 @author： xiaolin
 * 描述 ：Todo... 单个设置
 */
class ChatSetSingleActivity : BaseVMActivity<ChatViewModel, ActivitySetSingleBinding>() {
    override fun attachLayoutRes(): Int {
        return R.layout.activity_set_single
    }

    override fun attachVMClass(): Class<ChatViewModel>? {
        return ChatViewModel::class.java
    }
    override fun initBar() {
        super.initBar()
        mImmersionBar!!.statusBarDarkFont(true).init()
    }


    var bundle: Bundle? = null
    var userIdTa: String = ""
    var gid:String =""

    var isFriend = false //是否是好友

    var userMyId : String by Preference(HttpConstant.USER_ID, "")


    var isAdmin = false //他是否是管理员
    var isCanSay = false //他是否群内禁言
    var isNotInTeam = false // 不在群里
    var isShow= false

    var userInfoTa : GroupUserInfoDataBean? =null //他的信息


    override fun initView() {
        bundle = intent.extras
        gid=bundle!!.getString("gid","")
        userIdTa = bundle!!.getString("userIdTa", "")
        binding.run {
            bar.topTitle.text = "个人信息"
            bar.topLeftView.setOnClickListener { finish() }
        }
        if (TextUtils.isEmpty(gid)){
            //说明是个人
            binding.llAll.visible()
            binding.tvBtnFriend.visible()
            binding.llTemp.gone()
            binding.tvBtnGroupDel.gone()
            //查看是否是置顶状态
            ConversationRepo.isStickTop(userIdTa, SessionTypeEnum.P2P, object : ChatCallback<Boolean>() {
                override fun onSuccess(param: Boolean?) {
                    if (param!!) {
                        binding.ivSetTaboo.isSelected = true
                    }
                }
            })
        }else{
            //说明是群
            binding.llAll.gone()
            binding.tvBtnFriend.gone()
            upData()
        }

    }
    private fun upData() {
        /** 根据群id 查询个人信息 是否是管理员或者群主 **/
        val map: HashMap<String, Any> = HashMap()
        map["gid"] = gid
        map["userid"] = userIdTa
        loge("xxx===canshu ="+map.toString())
        GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onGroupUserInfoToMethod(it1) }

    }
    override fun onResume() {
        super.onResume()
        if (TextUtils.isEmpty(gid)){
            getUserInfoData()
        }
    }

    //查询用户名片
    fun  getUserInfoData(){
        val map: HashMap<String, Any> = HashMap()
        map["userid"] = userIdTa
        GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onGetUserInfoMethod(it1) }
    }


    override fun initClickListener() {
        super.initClickListener()
        binding.tvBtnChat.setSingleClickListener {
            //私聊
            RouterUtils.startToJumpSingleChat(this@ChatSetSingleActivity,userIdTa)

        }
        binding.llDelMsg.setSingleClickListener {
            //删除聊天记录
            XPopup.Builder(this@ChatSetSingleActivity)
                .popupAnimation(PopupAnimation.ScaleAlphaFromCenter  )
                .asCustom(
                    ConfirmCancelPopViiew(
                        this@ChatSetSingleActivity, "提示",  "确定要清除聊天记录吗?",
                        btnConfirm = {
                            NIMClient.getService(MsgService::class.java).clearChattingHistory(userIdTa, SessionTypeEnum.P2P,false)
                            NIMClient.getService(MsgService::class.java).clearServerHistory(userIdTa, SessionTypeEnum.P2P)
                            showToast("聊天记录已清除")
                            RxBus.getDefault().post(
                                RxBusBean(
                                    CustMsgType.CUST_RED_RESU_DEL,
                                    CustMsgType.CUST_RED_RESU_DEL
                                )
                            )
                            finish()
                        },
                        btnCancel = {
                        },
                    )
                )
                .show()





        }
        binding.llSetTop.setSingleClickListener {
            //置顶]
            if (binding.ivSetTaboo.isSelected){
                //取消置顶
                ConversationRepo.removeStickTop(
                    userIdTa,
                    SessionTypeEnum.P2P,
                    "",
                    object : FetchCallback<Void> {
                        override fun onSuccess(param: Void?) {
                            loge("removeStickTop==onSuccess")
                            binding.ivSetTaboo.isSelected = false
                            ConversationRepo.notifyStickTop(userIdTa, SessionTypeEnum.P2P)
                        }

                        override fun onFailed(code: Int) {
                        }

                        override fun onException(exception: Throwable?) {
                        }
                    })
            }else{
                ConversationRepo.addStickTop(
                    userIdTa,
                    SessionTypeEnum.P2P,
                    "",
                    object : ChatCallback<StickTopSessionInfo>() {
                        override fun onSuccess(param: StickTopSessionInfo?) {
                            binding.ivSetTaboo.isSelected = true
                            ConversationRepo.notifyStickTop(userIdTa, SessionTypeEnum.P2P)
                        }
                    })
            }

        }

        binding.tvBtnFriend.setSingleClickListener {
            if (isFriend){
               //删除好友
                XPopup.Builder(this@ChatSetSingleActivity)
                    .popupAnimation(PopupAnimation.ScaleAlphaFromCenter  )
                    .asCustom(
                        ConfirmCancelPopViiew(
                            this@ChatSetSingleActivity, "提示",  "确定要删除好友吗?",
                            btnConfirm = {
                                val map: HashMap<String, Any> = HashMap()
                                map["fuid"] = userIdTa!!
                                GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onDeleteFriendMethod(it1) }
                            },
                            btnCancel = {
                            },
                        )
                    )
                    .show()

            }else{
               //添加好友
                val map: HashMap<String, Any> = HashMap()
                map["fuid"] = userIdTa!!
                GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onAddFriendMethod(it1) }
            }
        }

        binding.llAdmin.setSingleClickListener{
            //设置他为管理员
            showLoading()
            val map: HashMap<String, Any> = HashMap()
            map["gid"] = gid!!
            map["userid"] = userIdTa
            map["ptype"] = if (isAdmin) 2 else 1
            map["minute"] = 0
            GsonUtil.mapToJsonStrObjEncryption(map)
                ?.let { it1 -> mViewModel.onGroupAdminMethod(it1) }
        }
        binding.ivSetJinYan.setSingleClickListener {
            //禁言
            showLoading()
            val map: HashMap<String, Any> = HashMap()
            map["gid"] = gid!!
            map["userid"] = userIdTa
            map["minute"] = 0
            map["ptype"] = if (isCanSay) 2 else 1
            GsonUtil.mapToJsonStrObjEncryption(map)
                ?.let { it1 -> mViewModel.onGroupStopuserMethod(it1) }
        }

        binding.tvBtnGroupDel.setSingleClickListener {
            //移除群
            XPopup.Builder(this@ChatSetSingleActivity)
                .popupAnimation(PopupAnimation.ScaleAlphaFromCenter  )
                .asCustom(
                    ConfirmCancelPopViiew(
                        this@ChatSetSingleActivity, "提示",  "确认要移除群组吗?",
                        btnConfirm = {
                            showLoading()
                            val map: HashMap<String, Any> = HashMap()
                            map["gid"] = gid!!
                            map["userids"] = userIdTa
                            map["ptype"] = 1
                            GsonUtil.mapToJsonStrObjEncryption(map)
                                ?.let { it1 -> mViewModel.onGroupJoinMethod(it1) }
                        },
                        btnCancel = {
                        },
                    )
                )
                .show()
        }
    }


    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {
            errorMsg.observe(this@ChatSetSingleActivity) {
                dismissLoading()
                showToast(it)
            }
            againLoginMsg.observe(this@ChatSetSingleActivity) {
                dismissLoading()
                showToast(CustKey.IN_AGAIN_MSG)
                LoginHelper.startLoginPage()
            }
            onGetUserInfoData.observe(this@ChatSetSingleActivity){
                GlideUtil.ImageHeadLoad(
                    this@ChatSetSingleActivity,
                    it.data.data.headimg,
                    binding.head
                )
                binding.tvName.text=it.data.data.nickname
                binding.tvBeiZhu.text=it.data.data.nickname
                if (TextUtils.isEmpty(gid)){
                    binding.tvBtnChat.gone()
                    isFriend = it.data.data.iffriend == 1
                    if (isFriend){
                        binding.tvBtnFriend.text="删除好友"
                        binding.llAll.visible()
                        //查询出来的用户信息
                        var mlistId= arrayListOf<String>()
                        mlistId.add(userIdTa)
                        NIMClient.getService(UserService::class.java).fetchUserInfo(mlistId).setCallback(object :
                            RequestCallback<List<NimUserInfo>> {
                            override fun onSuccess(result: List<NimUserInfo>?) {
                                if (result!=null){
                                    if (!TextUtils.isEmpty( result[0].extension)) {
                                        val json: String = result[0].extension
                                        Log.e("看看标签和等级", "===$json")
                                        var bean = Gson().fromJson(json, ExtDataBean::class.java)
                                        if (bean != null) {
                                            if (bean.ifzhaoshang != 0) {
                                                binding.llUserName.visible()
                                                if (bean.level == 0) {
                                                    binding.imgTag.setImageResource(com.netease.yunxin.kit.chatkit.ui.R.drawable.attract0)
                                                } else if (bean.level == 1) {
                                                    binding.imgTag.setImageResource(com.netease.yunxin.kit.chatkit.ui.R.drawable.attract1)
                                                } else if (bean.level == 2) {
                                                    binding.imgTag.setImageResource(com.netease.yunxin.kit.chatkit.ui.R.drawable.attract2)
                                                }
                                                //等级
                                                binding.tvAgent.text = bean.area + "服务中心"
                                            }
                                        }else binding.llUserName.gone()
                                    }
                                }
                            }

                            override fun onFailed(code: Int) {
                            }

                            override fun onException(exception: Throwable?) {
                            }

                        })

                    }else{
                        binding.tvBtnFriend.text="添加好友"
                        binding.llAll.gone()
                    }
                }
            }

            onGroupUserInfoToData.observe(this@ChatSetSingleActivity){
                //这是查询他在群里的信息
                userInfoTa = it.data.data
                if (userMyId==userIdTa){
                    binding.llTemp.gone()
                    binding.tvBtnGroupDel.gone()
                    binding.tvBtnChat.gone()
                    getUserInfoData()
                }else{
                    GlideUtil.ImageHeadLoad(
                        this@ChatSetSingleActivity,
                        it.data.data.headimg,
                        binding.head
                    )
                    binding.tvName.text=it.data.data.nickname
                    binding.tvBeiZhu.text=it.data.data.nickname
                    //查询自己在群里的权限
                    /** 根据群id 查询个人信息 是否是管理员或者群主 **/
                    val map: HashMap<String, Any> = HashMap()
                    map["gid"] = gid
                    map["userid"] = userMyId
                    loge("xxx===canshu ="+map.toString())
                    GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onGroupUserInfoMethod(it1) }
                }
            }
            onGroupUserInfoData.observe(this@ChatSetSingleActivity){
                //查看自己的权限 // 群里角色 9 群主 8管理员 0 普通用户
                var roles = it.data.data.roles
                if(roles==9){
                    //群主
                    binding.llTemp.visible()
                    binding.tvBtnGroupDel.visible()
                    binding.llAdmin.visible()
                    binding.tvxian.visible()
                    binding.llJinYang.visible()
                    //如果他是管理员的话
                    binding.ivSetAdmin.isSelected = userInfoTa!!.roles==8
                    isAdmin = userInfoTa!!.roles==8
                    //1是false正常  否则 就是禁言状态
                    if(userInfoTa!!.cansay==1){
                        //1是false正常  否则 就是禁言状态
                        isCanSay=false
                        binding.ivSetJinYan.isSelected=false
                    }else{
                        isCanSay=true
                        binding.ivSetJinYan.isSelected=true
                    }

                }else if(roles==8){
                    //管理员
                    if(userInfoTa!!.roles==8 || userInfoTa!!.roles==9){
                        //他是否是管理员或者群主
                        binding.llTemp.gone()
                        binding.tvBtnGroupDel.gone()
                        //如果对方是管理员的话。没有权限T对方
                        isShow=false
                        isAdmin=true
                    }else{
                        isAdmin=false
                        binding.llTemp.visible()
                        binding.tvBtnGroupDel.visible()
                        binding.ivSetAdmin.isSelected =false
                        if(userInfoTa!!.cansay==1){
                            //1是false正常  否则 就是禁言状态
                            isCanSay=false
                            binding.ivSetJinYan.isSelected=false
                        }else{
                            isCanSay=true
                            binding.ivSetJinYan.isSelected=true
                        }
                    }
                }else{
                    binding.llTemp.gone()
                    binding.tvBtnGroupDel.gone()
                }
                binding.tvBtnChat.visibility =  if (it.data.data.cansixin==1) View.VISIBLE else View.GONE
            }
            onGroupAdminData.observe(this@ChatSetSingleActivity){
                //设置他为管理员
                dismissLoading()
                showToast("设置成功!")
                /** 根据群id 查询个人信息 是否是管理员或者群主 **/
                upData()
            }
            onGroupStopuserData.observe(this@ChatSetSingleActivity){
                //禁言
                dismissLoading()
                showToast("设置成功!")
                /** 根据群id 查询个人信息 是否是管理员或者群主 **/
                upData()
            }
            onGroupJoinData.observe(this@ChatSetSingleActivity){
                //移除群
                dismissLoading()
                showToast("移除成功")
                finish()
            }
            onDeleteFriendData.observe(this@ChatSetSingleActivity){
                showToast("删除成功")
                RxBus.getDefault().post(
                    RxBusBean(CustSignKey.IM_DELETE_INFO, CustSignKey.IM_DELETE_INFO,userIdTa)
                )
                var mlistId= arrayListOf<String>()
                mlistId.add(userIdTa)
                NIMClient.getService(MsgService::class.java).deleteRecentContact2(userIdTa, SessionTypeEnum.P2P)
                finish()
            }
            onAddFriendData.observe(this@ChatSetSingleActivity){
                showToast("申请成功")
            }
        }
    }
}